package com.iob.coin.blImpl.identify;

import com.iob.coin.DAO.UserDAO;
import com.iob.coin.bl.identify.IdentifyService;
import com.iob.coin.po.User;
import com.iob.coin.util.UserSessionUtil;
import com.iob.coin.util.logutil.Logger;
import com.iob.coin.vo.ResponseVO;
import com.iob.coin.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: GuoXinyuan
 * @Date: 2021/5/28
 */
@Service
public class IdentifyServiceImpl implements IdentifyService {

    @Autowired
    UserDAO userDAO;

    Logger logger = new Logger(this.getClass().getSimpleName(),System.out);

    @Override
    public ResponseVO currentUser() {
        Integer userid = UserSessionUtil.getLoginUserId();
        if(userid == null) return ResponseVO.buildFailure("服务器错误");
        User user = userDAO.findById(userid);
        return ResponseVO.buildSuccess(user);
    }

    @Override
    public ResponseVO register(UserVO userVO) {
        if(userDAO.findUserByUsername(userVO.getUsername()).size() > 0){
            return ResponseVO.buildFailure("用户名已存在");
        }
        User user = new User();
        user.setUsername(userVO.getUsername());
        user.setPassword(userVO.getPassword());
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));

        userDAO.save(user);

        logger.log("register","用户注册",new HashMap<String,String>(){{
            put("username", userVO.getUsername());
            put("password", userVO.getPassword());
        }});

        return ResponseVO.buildSuccess();
    }

    @Override
    public ResponseVO login(UserVO userVO) {
        List<User> existsUserList = userDAO.findUserByUsername(userVO.getUsername());

        if(existsUserList.size() == 0) return ResponseVO.buildFailure("用户名或密码错误");
        else if(existsUserList.size() > 1) return ResponseVO.buildFailure("未知错误");

        User curUser = existsUserList.get(0);

        if(!curUser.getPassword().equals(userVO.getPassword())) return ResponseVO.buildFailure("密码错误");

        userVO.setId(curUser.getId());
        userVO.setCreateTime(curUser.getCreateTime().toString());
        userVO.setSetting(curUser.getSetting());

        //设置登录的会话
        UserSessionUtil.setUserLoginState(curUser.getId());

        logger.log("login","用户登录",new HashMap<String,String>(){{
            put("username", userVO.getUsername());
            put("password", userVO.getPassword());
        }});

        return ResponseVO.buildSuccess(userVO);
    }

    @Override
    public ResponseVO logout() {
        logger.log("logout","用户注销",new HashMap<String,String>(){{
            put("userId", String.valueOf(UserSessionUtil.getLoginUserId()));
        }});

        UserSessionUtil.removeUserLoginState();

        return ResponseVO.buildSuccess();
    }
}
